package com.dp.mallchat.common.user.service.adapter;

import com.dp.mallchat.common.user.domain.user.entity.ItemConfig;
import com.dp.mallchat.common.user.domain.user.entity.User;
import com.dp.mallchat.common.user.domain.user.entity.UserBackpack;
import com.dp.mallchat.common.user.domain.user.resp.BadgeResp;
import com.dp.mallchat.common.user.domain.user.resp.UserInfoResp;
import me.chanjar.weixin.common.bean.WxOAuth2UserInfo;
import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author: dupeng
 * @CreateTime: 2024-05-23  18:36
 * @Description: TODO
 */
public class UserAdapter {


    public static User buildUser(Long uid, WxOAuth2UserInfo wxOAuth2UserInfo){
        return User.builder()
                .id(uid)
                .avatar(wxOAuth2UserInfo.getHeadImgUrl())
                .name(wxOAuth2UserInfo.getNickname())
                .sex(wxOAuth2UserInfo.getSex())
                .build();
    }


    public static UserInfoResp buildUserInfoResp(User user, Integer waitUseCount) {
        return UserInfoResp.builder()
                .uid(user.getId())
                .avatar(user.getAvatar())
                .name(user.getName())
                .sex(user.getSex())
                .modifyNameChance(waitUseCount)
                .build();
    }

    public static List<BadgeResp> buildBadgesBuild(List<ItemConfig> itemConfigList, List<UserBackpack> userBackpackList, User user) {

        Set<Long> badges = null;
        if (!CollectionUtils.isEmpty(userBackpackList)) {
            badges = userBackpackList.stream().map(UserBackpack::getItemId).collect(Collectors.toSet());
        }

        Set<Long> finalBadges = badges;
        return itemConfigList.stream().map(item -> {
            BadgeResp badgeResp = new BadgeResp();
            BeanUtils.copyProperties(item, badgeResp);
            if (!CollectionUtils.isEmpty(finalBadges)) {
                badgeResp.setObtain(finalBadges.contains(item.getId()) ? 1 : 0);
                badgeResp.setWearing(item.getId().equals(user.getItemId()) ? 1 : 0);
            }
            return badgeResp;
        }).sorted(Comparator.comparing(BadgeResp::getWearing, Comparator.reverseOrder())
                .thenComparing(BadgeResp::getObtain, Comparator.reverseOrder()))
                .collect(Collectors.toList());
    }
}
